import React from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'react-redux'
import util from '../../util'
import cx from 'classnames'
import { bindActionCreators } from 'redux'
import * as okrAction from '../../actions/okr.action'
import { fetchProfile, setStepGuide, updateGuide } from '../../actions/app.action'
import { fetchAtList, clearAtList } from '../../actions/home.action'
import { resetUser, fetchUserCoreProfile } from '../../actions/user.action'
import { fetchTeamAncestorChildren, fetchTeam, resetTeam } from '../../actions/team.action'
import { verifyPassword } from '../../actions/auth.action'
import { u } from '../../actions/util'
import style from './style.objective';
import { Select, SearchInput, Avatar, Loading, Menu, Input, IconButton, DraggableList, Progress, Link, Button, InlineButton, IconFont, List } from 'sq-ui';
import { Checkbox, Modal, info, error, success, FileUpload } from '../../ui-components';
import { Motion, TransitionMotion, spring, presets } from 'react-motion';
import ObjectiveItem from './ObjectiveItem';
import ObjectiveCreate from './ObjectiveCreate';
import ObjectiveTest from "./ObjectiveTest";
import ObjectiveNote, { pageSize as commentsPageSize } from './ObjectiveNote';
import { NextGuide } from '../guide/Guide';
import Upload from 'component-upload';
import cookie from 'component-cookie';

import ObjectiveDrag from './plugins/ObjectiveDrag';

// 创建关键结果
export
function createKeyResult() {
    const { field } = this.refs.objectiveCreate.state;
    const {
        startingAmount,
        currentAmount,
        ...others,
    } = field;

    if (checkItemInput(field) !== true) return;
    info('创建中...');
    this.props.actions.createKeyResult({ startingAmount, currentAmount, ...others }, () => {
        success('创建成功!');
        if (this.fetchObjective) {
            this.fetchObjective();
        } else {
            this.fetchContent(null, null, null, true);
        }

        if (this.props.app.naviStep == 4 && this.props.app.guide == 3) {
            this.props.actions.updateGuide(5);
        }
    });
    cancelRequestCreateItem.call(this);
}

export
function cancelRequestCreateItem() {
    this.setState({
        createItem: false,
        objectiveId: null,
    }, () => {
        setTimeout(() => {
            this.setState({
                createObjective: false,
                createKeyResult: false,
            })
        }, 200)
    })
}
// 编辑目标
export
function requestEditObjective(objective) {
    this.setState({
        editItem: true,
        editObjective: true,
        objective,
    });
}

// 编辑结果
export
function requestEditKeyResult(keyResult) {
    this.setState({
        editItem: true,
        editKeyResult: true,
        keyResult,
    });
}

let preObjId = null, preObjFlag = true, preKrId = null, preKrFlag = true;

// 点赞目标
function likeObjective(obj, thumb) {
    const { okr, profile } = this.props;
    let { objective } = okr;
    let { thumbup } = objective;
    let { userId } = profile;
    if(!preObjFlag) return;
    preObjFlag = false;
    const { orgId, objectiveId } = obj;
    let arg = {
        userId, orgId, okrId: objectiveId, keyResultId: null, type: 0, comment: ""
    };
    this.props.actions.updateThumpBub(arg, (res) => {
        const {data} = res;
        thumbup.forEach(item => {
            if(item.okrId == data.okrId){
                item.isThumpBup = data.isThumpBub;
                item.total = data.total;
            }
        });
        this.setState({
            objective
        }, () => {
            preObjFlag = true;
        });
    });
}

// 点赞结果
function likeKeyResult(thumb, kr) {
    const { okr, profile } = this.props;
    let { objective } = okr;
    let { thumbup } = objective;
    let { userId } = profile;
    if(!preKrFlag) return;
    preKrFlag = false;
    const { orgId, objectiveId, keyResultId} = kr;
    let arg = {
        userId, orgId, okrId: objectiveId, keyResultId, type: 1, comment: ""
    };
    this.props.actions.updateThumpBub(arg, (res) => {
        const { data } = res;
        thumbup.forEach(item => {
            if(item.okrId == data.okrId){
                let { thumpBupKeyResultVOs } = item;
                thumpBupKeyResultVOs.forEach(element => { // 判断结果点赞
                    if(element.keyResultId == data.keyResultId){
                        element.isThumpBup = data.isThumpBub;
                        element.total = data.total;
                    }
                })
            }
        });
        this.setState({
            objective
        }, () => {
            preKrFlag = true;
        });
    });
}

export
function cancelRequestEditItem() {
    this.setState({
        editItem: false,
    }, () => {
        setTimeout(() => {
            this.setState({
                editObjective: false,
                editKeyResult: false,
            });
        }, 200);
    })
}

export
function requestCreateKeyResult(objectiveId) {
    this.setState({
        createKeyResult: true,
        createItem: true,
        objectiveId,
    });
}

// 更新目标
export
function updateObjective() {
    const { objectiveId, ...others } = this.refs.objectiveEdit.state.field;
    const { selectObjective } = this.refs.objectiveEdit.state;
    if (checkItemInput.call(this, this.refs.objectiveEdit.state.field) !== true) return;

    if (!util.isNull(selectObjective)) {
        others.parentObjectiveId = selectObjective.objectiveId;
    } else {
        others.parentObjectiveId = '2B1E6D025AC28868';
    }

    info('更新中...');
    this.props.actions.updateObjective(objectiveId, others, () => {
        if (this.fetchObjective) {
            this.fetchObjective();
            if (this.props.app.naviStep == 6 && this.props.app.guide == 3) {
                this.props.actions.updateGuide(7);
            }
        } else {
            this.refreshObjective();
        }

        if(this.props.app.naviStep == 6 && this.props.app.guide == 3){
            const {
                org
            } = this.props.app;
            setTimeout(()=>{
                this.context.router.push(`/okr?type=1&teamId=${(org.teamVO || {}).teamId}`);
            }, 0);
        }

        success('更新成功!');
    });

    cancelRequestEditItem.call(this);
}

// 更新结果
export
function updateKeyResult() {
    const { keyResultId, objectiveId, ...others } = this.refs.objectiveEdit.state.field;
    if (checkItemInput.call(this, this.refs.objectiveEdit.state.field) !== true) return;

    info('更新中...');
    this.props.actions.updateKeyResult(keyResultId, objectiveId, others, () => {
        if (this.fetchObjective) {
            this.fetchObjective();
        } else {
            this.refreshKeyResult();
        }
        success('更新成功!');
    })

    cancelRequestEditItem.call(this);
}

// 检查结果
export
function checkItemInput(obj) {
    const {
        content,
        currentAmount,
        startingAmount,
        goalAmount,
        progressMetricType,
    } = obj;

    if (!content.trim()) return error('内容不能为空');
    if (currentAmount === '') return error('当前值不能为空');
    if (startingAmount === '') return error('初始值不能为空');
    if (goalAmount === '') return error('目标值不能为空');
    if (progressMetricType != 1) {
        if (!/^-?(\d+)?\.?\d+$/.test(currentAmount)) return error('当前值只能是数字');
        if (!/^-?(\d+)?\.?\d+$/.test(startingAmount)) return error('初始值只能是数字');
        if (!/^-?(\d+)?\.?\d+$/.test(goalAmount)) return error('目标值只能是数字');
    } else {
        if (!/^\d+$/.test(currentAmount)) return error('当前值只能是正整数');
    }

    return true;
}

export
function checkCurrentAmount(value) {
    if (value.trim()) {
        if (+value !== 0 && !(+value) || /\./.exec(value) || value > 100 || value < 0) return false;
        else {
            value = +value;
        }
    }
    return value;
}

const IMAGES_PATH = process.env.NODE_ENV === 'production'? './static/images': './static/src/images'

const COMPANY = 1; // 公司
const TEAM = 2; // 团队
const PERSONAL = 3; // 个人
const GROUP = 4; // 全部
const ROOT_TEAM = '2B1E6D025AC28868';

// 最近查看and搜索
/*
function Search(props) {
  const { ctx, searching, okrHistory, okr, query, app } = props;
  const { search } = okr;
  const { teamVO } = app.org;

  function render(obj) {
    const { teamVOs, coreUserProfileVOs, projectTeamVOs } = obj;

    if (!teamVOs.length && !coreUserProfileVOs.length && !projectTeamVOs.length) return (
      <div style={{ marginLeft: '20px' }}>没有数据.</div>
    );

    let teams;
    let users;
    let groups;

    if (teamVOs.length) {
      teams =
        <ul>
          {
            teamVOs.filter(t => t.teamId != (teamVO || {}).teamId).map((team, i) => (
              <li key={i}>
                <Link
                  to={`/okr?type=${TEAM}&teamId=${team.teamId}`}
                  onClick={() => ctx.setState({ query: '' })}
                >
                  <span className={style['team-span']}>
                    <Avatar
                      team
                      width={36}
                    />
                    <span>{team.teamName}</span>
                  </span>
                </Link>
              </li>
            ))
          }
        </ul>;
    }

    if (coreUserProfileVOs.length) {
      users =
        <ul>
          {
            coreUserProfileVOs.map((user, i) => (
              <li key={i}>
                <Link
                  to={`/okr?type=${PERSONAL}&userId=${user.userId}&teamId=${user.teamVO.teamId}`}
                  onClick={() => ctx.setState({ query: '' })}
                >
                  <span className={style['user-span']}>
                    <span>
                      <Avatar
                        src={user.avatarUrl}
                        width={36}
                      />
                      <span>{user.fullName}</span>
                    </span>
                    <span className={style['title']}>{user.jobTitleName || ''}</span>
                  </span>
                </Link>
              </li>
            ))
          }
        </ul>
    }

    if (projectTeamVOs.length) {
      groups =
        <ul>
          {
            groups.map((g, i) => (
              <li key={i}>
                <Link
                  to={`/okr?type=${GROUP}&projectTeamId=${g.projectTeamId}&teamId=${g.teamId}`}
                  onClick={() => ctx.setState({ query: '' })}
                >
                  <span className={style['user-span']}>
                    <span>
                      <Avatar
                        team
                        width={36}
                      />
                      <span>{g.projectTeamName}</span>
                    </span>
                  </span>
                </Link>
              </li>
            ))
          }
        </ul>
    }

    return (
      <div>
        { teams }
        { users }
        { groups }
      </div>
    );
  }

  // 搜索
  if (query) {
    // loading...
    if (util.isNull(search) || searching) return <Loading small className={style['loading-recent']}/>;
    return render(search);
  }

  // 最近查看
  else {
    // loading...
    if (util.isNull(okrHistory) || searching) return <Loading small className={style['loading-recent']}/>;
    return render(okrHistory);
  }
}
*/

// 周期操作列表
function ActionList(props) {
    const {
        className,
        creatable,
        deletable,
        onClose,
        app,
        actions,
    } = props;
    const hasPeriod = props.params.periodId;
    const { naviStep: step, nextGuide } = app;
    return (
        <ul className={cx(className, style['action-list'])}>
            {
                creatable?
                    <li>
                        <Link
                            onClick={() => {
                                onClose();
                                props.requestCreatePeriod();
                                actions.setStepGuide(3);
                            }}
                            label="创建新周期"
                        />
                    </li>: null
            }
            {
                (creatable && hasPeriod)?
                    <li>
                        <Link onClick={() => { onClose(); props.requestEditPeriod(); }} label="更新当前周期"/>
                    </li>: null
            }
            {
                (deletable && hasPeriod)?
                    <li>
                        <Link className={style['delete-period']} onClick={() => { onClose(); props.requestDeletePeriod(); }} label="删除当前周期"/>
                    </li>: null
            }
        </ul>
    );
}

export default
@connect(({ okr, app, user, team }) => ({ okr, app, user, team }), dispatch => ({actions: bindActionCreators({...okrAction, verifyPassword,fetchAtList, clearAtList, fetchUserCoreProfile, resetUser, resetTeam, fetchProfile, fetchTeamAncestorChildren, fetchAtList, clearAtList, setStepGuide, updateGuide }, dispatch)}))
class Objective extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object,
        onContentScroll: React.PropTypes.func.isRequired,
    }
    state = {
        // newTest: false, // 测试弹窗
        showChildren: false,
        showTeamMemebers: false,
        showGroupMembers: false,
        showTeamGroups: false,
        showOtherTeamUsers: false,
        canMove: false,
        createItem: false,
        createObjective: false,
        createKeyResult: false,
        // 创建关键结果的目标Id
        objectiveId: null,
        deletePeriod: false,
        createPeriod: false,
        editPeriod: false,
        createEditPeriod: false,
        search: false,
        searching: false,
        query: '',
        editItem: false,
        editObjective: false,
        editKeyResult: false,
        objective: null,
        keyResult: null,
        deletePeriodName: null,
        deletePassword: '',
        deleteMsg: '',
        // 其他团队的子团队
        otherTeamChildren: {},
        showOtherTeam: null,
        showCompanyChildrenObjectives: false,
    }

    // 编辑周期时所选的周期选项对象
    editPeriodItem = null

    handleSearch(e) {
        const query = e.target.value.trim();

        this.setState({
            query
        });

        if (e.target.value.length && !query) return;

        this.setState({
            searching: true
        })
        if (!query) {
            this.props.actions.fetchOkrHistory(() => {
                this.setState({
                    searching: false
                })
            });
        } else {
            util.throttle(
                () => {
                    this.props.actions.searchTeamsAndUsers(query, () => {
                        this.setState({
                            searching: false
                        })
                    });
                }
            );
        }
    }

    toggleSearch() {
        if (!this.state.search) {
            this.setState({
                searching: true
            });
            if (this.state.query.trim()) {
                this.props.actions.searchTeamsAndUsers(this.state.query.trim(), () => {
                    this.setState({
                        searching: false
                    });
                });
            } else {
                this.props.actions.fetchOkrHistory(() => {
                    this.setState({
                        searching: false
                    });
                });
            }
        } else {
            setTimeout(() => {
                this.props.actions.resetOkrSearch();
            }, 150)
        }

        setTimeout(() => {
            this.setState({
                search: !this.state.search,
                searching: false,
                stopSearch: false,
            });
        }, 150)
    }

    // 团队内所有目标
    handleCheckAllTeamObjective() {
        const { query, pathname } = this.props.location;
        const { aboutMe, progressStatus, ...others } = query;
        this.context.router.push({
            query: {
                progressStatus: 1,
                ...others,
            },
            pathname,
        });
    }

    // 团队内根据我的筛选
    handleToggleAboutMe() {
        const { query, pathname } = this.props.location;
        const { aboutMe } = query;
        this.context.router.push({
            query: {
                ...query,
                aboutMe: !((aboutMe === 'false' || !aboutMe)? false: true),
            },
            pathname,
        });
    }

    // 团队内根据进度筛选
    handleChangeProgressStatus(value) {
        const { query, pathname } = this.props.location;
        this.context.router.push({
            query: {
                ...query,
                progressStatus: +value+1,
            },
            pathname,
        });
    }

    // 创建周期
    createPeriod() {
        const { editPeriodItem } = this;
        if (!editPeriodItem) return;
        const { type, teamId, userId, projectTeamId } = this.props.location.query
        const { periodTimeSpanId, name, year } = editPeriodItem;
        let ownerId = type == PERSONAL ? userId : type == GROUP ? projectTeamId : teamId;
        if (type == COMPANY) ownerId = null;
        info('创建周期中...')
        this.props.actions.createPeriod({ type, periodTimeSpanId, name, year, ownerId }, () => {
            success('创建目标周期成功!')
            this.editPeriodItem = null;
            this.fetchPeriod()

            if (this.props.app.naviStep == 2 && this.props.app.guide == 3) {
                this.props.actions.updateGuide(3);
            }

        })
        setTimeout(() => {
            this.cancelRequestCreateEditPeriod();
        }, 0)
    }

    // 更新周期
    updatePeriod() {
        const { editPeriodItem } = this;
        if (!editPeriodItem) return;
        const { periodId } = this.props.params
        const { periodTimeSpanId, name, year } = editPeriodItem;
        info('更新周期中..')
        this.props.actions.updatePeriod(periodId, { periodTimeSpanId, name, year }, () => {
            success('更新周期成功!');
            this.editPeriodItem = null;
            this.fetchPeriod();
        });
        setTimeout(() => {
            this.cancelRequestCreateEditPeriod();
        }, 0);
    }

    handleCanMove(can) {
        this.setState({
            canMove: can === false? false: true
        })
    }

    addHistory(props) {
        props = props || this.props;
        const { teamId, userId } = props.location.query;
        if (!teamId && !userId) return;
        // 除了自己和公司外，其他目标页添加到历史记录
        if (!util.isEqual(userId, u.userId) && this.type(props) != COMPANY) {

            if (this.type(props) == TEAM) {
                //console.log('添加team历史纪录');
                this.props.actions.addViewHistory({ teamId });
            } else if (this.type(props) == PERSONAL) {
                //console.log('添加个人历史纪录');
                this.props.actions.addViewHistory({ userId });
            }
        }
    }

    handleAncesterTeam(props) {

        const { teamAncestorChildren } = props.team;
        const { ancestorTeams=[] } = teamAncestorChildren;
        const { teamId } = props.app.org.teamVO || {};

        const teams = ancestorTeams.filter(t => t.teamId != teamId);

        teams.forEach(({ teamId, parentTeamId }) => this.props.actions.fetchTeamAncestorChildren(parentTeamId, res => {
            this.setState({
                otherTeamChildren: {
                    ...this.state.otherTeamChildren,
                    [teamId]: res.data.childrenTeams.filter(t => t.teamId != teamId),
                }
            })
        }))
    }

    fetchGroupTeam(props) {
        const { projectTeamId } = (props || this.props).location.query;
        this.props.actions.fetchGroupTeam(projectTeamId, (res) => {
            const { teamId } = res.data;
            this.context.router.replace({
                pathname: this.props.location.pathname,
                query: {
                    ...this.props.location.query,
                    teamId,
                }
            });
        });
    }

    componentDidMount() {
        this.fetchPeriod();
        this.fetchObjective(); // 获取所有目标
        this.fetchNav();
        this.fetchTeamMembers();
        this.fetchTeamGroups();
        this.fetchGroupMembers();
        this.fetchUserCoreProfile();


        // 添加历史纪录
        this.addHistory();
        const {
            path,
            query,
        } = this.props.location;
        //添加统计
        if(path !== '/okr'){
            util.trackOkrList(query.type);
        }

        if (+this.type() === GROUP) {
            if (query.teamId === undefined) {
                this.fetchGroupTeam();
            }
        }
    }

    componentWillReceiveProps(props) {

        const { query, pathname, path } = props.location;
        const { periodId } = props.params;
        const { periodId: prevPeriodId } = this.props.params;
        const { query: prevQuery } = this.props.location;
        const { objective, period, periodLevel } = props.okr;
        const { period: prevPeriod, periodLevel: prevPeriodLevel } = this.props.okr;
        const { projectTeamId, teamId, userId, type } = query;
        const { projectTeamId: prevProjectTeamId, teamId: prevTeamId, userId: prevUserId, type: prevType } = prevQuery;


        //添加统计
        if(path !== '/okr' && !!prevPeriodId && prevPeriodId !== periodId){
            util.trackOkrList(type);
        }

        const { one: levelOne, two: levelTwo } = periodLevel;
        const { one: prevLevelOne, two: prevLevelTwo } = prevPeriodLevel;


        // 针对team处理没有teamId的情况
        if (this.type(props) == TEAM) {
            if (util.isNull(prevPeriod) && !util.isNull(period)) {
                const { objectivePeriods } = period;
                if (!teamId) {
                    if (!util.isNull(objectivePeriods)) {
                        const { pathname, query } = props.location;
                        this.context.router.replace({
                            query: {
                                ...query,
                                teamId: objectivePeriods[0].ownerId,
                            },
                            pathname,
                        });
                    }
                }
            }
        }

        // 针对个人处理没有teamId的情况
        if (this.type(props) == PERSONAL) {
            if (!teamId) {
                const { coreProfile } = props.user;
                //console.log('no teamId');
                if (util.isNull(this.props.user.coreProfile) && !util.isNull(coreProfile)) {
                    // 防止没有team的时候
                    const { teamId } = coreProfile.teamVO || {};
                    if (teamId) {
                        const { pathname, query } = props.location;
                        this.context.router.replace({
                            query: {
                                ...query,
                                teamId,
                            },
                            pathname,
                        });
                    }
                }
            }
        }

        if (util.isNull(this.props.team.teamAncestorChildren) && !util.isNull(props.team.teamAncestorChildren)) {
            this._teamAncestorChildren = props.team.teamAncestorChildren;
            if (!util.isNull(props.app.org)) {
                this.handleAncesterTeam(props);
            }
        }

        if (util.isNull(this.props.app.org) && !util.isNull(props.app.org)) {
            if (this._teamAncestorChildren) {
                this.handleAncesterTeam(props);
            }
        }

        if ((levelOne && levelTwo && !util.isShallowEqual(levelOne, prevLevelOne))) {
            this.props.actions.fetchPeriodLevelTwo({
                type: levelOne.filter(v => v.default)[0].type,
            });
        }

        if ((levelOne && !levelTwo)) {
            //console.log('没有levelTwo');
            // 创建周期
            if (this.state.createPeriod) {
                this.props.actions.fetchPeriodLevelTwo({
                    type: levelOne.filter(v => v.default)[0].type,
                });
            }
            //  编辑周期
            else if (this.state.editPeriod) {
                const currentPeriod = period.objectivePeriods.filter(v => v.objectivePeriodId == periodId)[0];
                const { year, periodTimeSpanId } = currentPeriod
                this.props.actions.fetchPeriodLevelTwo({
                    type: levelOne.filter(v => v.default)[0].type,
                    year,
                    periodTimeSpanId,
                });
            }
        }

        // 前一个周期列表已经读完
        if (Array.isArray(prevPeriod.objectivePeriods)) {
            const { objectivePeriods } = period;
            if (Array.isArray(objectivePeriods)) {
                // 新建周期
                if (objectivePeriods.length > prevPeriod.objectivePeriods.length) {

                    //console.log('多出了一个周期~~, 跳转到新周期~~');
                    const newPeriod = objectivePeriods.filter(p => prevPeriod.objectivePeriods.every(_p => _p.objectivePeriodId != p.objectivePeriodId))[0];

                    this.context.router.push({
                        query,
                        pathname: `/okr/${newPeriod.objectivePeriodId}/objectives`
                    });
                }
                // 删除周期
                else if (objectivePeriods.length < prevPeriod.objectivePeriods.length) {
                    //console.log('少了一个周期~~');
                    const oldPeriodId = this.getCurPeriod(objectivePeriods);
                    if (oldPeriodId) {
                        //console.log('还有其他周期，跳转~~');
                        this.context.router.replace({
                            query,
                            pathname: `/okr/${oldPeriodId}/objectives`
                        });
                    } else {
                        //console.log('没有周期了~~');
                        this.context.router.replace({
                            query,
                            pathname: '/okr'
                        });
                    }
                }
            }
        }

        const { aboutMe, progressStatus, ...queryOthers } = query;
        const { aboutMe: prevAboutMe, progressStatus: prevProgressStatus, ...prevQueryOthers } = prevQuery;

        if (!util.isShallowEqual({ aboutMe, progressStatus }, { aboutMe: prevAboutMe, progressStatus: prevProgressStatus })) {
            //console.log('团队内筛选条件变化~~, 重新读取目标');
            this.fetchObjective(props, null, true);
        }

        if (!util.isShallowEqual(queryOthers, prevQueryOthers)) {
            this.reset();
            //console.log('周期变化');
            if (!periodId || periodId != prevPeriodId) {
                // 重置周期
                this.fetchPeriod(props);
            }

            if (teamId != prevTeamId || type != prevType) {
                //console.log('团队发生变化，重新读取');
                this.fetchNav(props);
                this.setState({
                    otherTeamChildren: {},
                    showOtherTeam: null,
                    showTeamGroups: null,
                });
                this.props.actions.resetTeamMembers();
                this.props.actions.resetTeam();
                this._teamAncestorChildren = null;
                if (type != PERSONAL && type != GROUP) {
                    this.fetchTeamMembers(props);
                }

                if (type != PERSONAL) {
                    this.fetchTeamGroups(props);
                }
            }

            if (projectTeamId != prevProjectTeamId) {
                this.setState({
                    showGroupMembers: null,
                    showTeamGroups: null,
                });
                this.fetchTeamGroups(props);
                this.fetchGroupMembers(props);
            }

            if (userId != prevUserId) {
                //console.log('人员发生了变化，重新读取');
                this.fetchUserCoreProfile(props);
                this.fetchTeamMembers(props);
            }

            // 添加历史纪录
            if (userId != prevUserId || teamId != prevTeamId) {
                this.addHistory(props);
            }

            if (!periodId) {
                return;
            }
        }

        if (!periodId && !prevPeriodId) {
            //console.log('存在周期数据, 但是没有周期Id');
            const curPeriodId = this.getCurPeriod(period.objectivePeriods);
            if (curPeriodId) {
                this.context.router.replace({
                    query,
                    pathname: `/okr/${curPeriodId}/objectives`,
                });
            }
        }

        if (periodId != prevPeriodId) {
            //console.log('搞到了新周期Id, 去读取目标~~');
            this.fetchObjective(props);
        }

    }

    componentWillUnmount() {
        this.props.actions.resetOkr();
        this.props.actions.resetUser();
        this.props.actions.resetTeam();
    }

    componentWillUpdate(props) {
        // 引导
        const { naviStep: nextStep, guide: nextGuide } = props.app;
        const { naviStep, guide } = this.props.app;

        if (nextStep == 2 && nextGuide == 2 && guide == 1) {
            setTimeout(() => {
                this.refs.periodMenu.setState({
                    clicked: true,
                });
            }, 150);
        }

        if (props.app.naviStep === 3 && props.app.guide == 2 && this.props.app.guide == 1) {
            setTimeout(() => {
                findDOMNode(this.props.root).scrollTop = 9999;
            }, 150)
        }
        if (props.app.naviStep === 4 && props.app.guide == 2 && this.props.app.guide == 1) {
            setTimeout(() => {
                findDOMNode(this.props.root).scrollTop = 315;
            }, 150)
        }

        if ((props.app.naviStep === 5 || props.app.naviStep === 6 || props.app.naviStep === 7) && props.app.guide == 2 && this.props.app.guide == 1) {
            setTimeout(() => {
                findDOMNode(this.props.root).scrollTop = 0;
            }, 150)
        }
    }

    reset() {
        //console.log('reset okr');
        this.props.actions.resetOkr();
        this.setState({
            showChildren: false,
            showTeamMemebers: false,
            showOtherTeamUsers: false,
        });
    }

    handleChangeSelectPeriodLevel(value) {
        this.props.actions.updatePeriodLevelOne(value)
    }

    handleChangeSelectPeriodLevelTwo(_, item) {
        this.editPeriodItem = item;
        this.props.actions.updatePeriodLevelTwo(item)
    }

    deletePeriod() {

        if(!this.state.deletePassword){
            this.setState({
                deleteMsg: '密码不能为空',
            });
            return;
        }
        this.props.actions.verifyPassword(this.state.deletePassword,(d) =>{
            if(!d.data) {
                this.setState({
                    deleteMsg: '密码错误',
                });
                return;
            }
            info('删除中...');
            this.props.actions.resetObjective();
            this.props.actions.deletePeriod(this.props.params.periodId, () => {
                const { objectivePeriods } = this.props.okr.period;
                const periodId = this.getCurPeriod(objectivePeriods.filter(p => p.objectivePeriodId != this.props.params.periodId));
                const { query } = this.props.location;

                if (periodId) {
                    this.fetchPeriod();
                    this.context.router.push({
                        query,
                        pathname: `/okr/${periodId}/objectives`
                    });
                } else {
                    this.props.actions.clearPeriods();
                    this.context.router.push({
                        query,
                        pathname: 'okr'
                    })
                }
                success('删除周期成功!');
                this.cancelRequestDeletePeriod();
            });
        });
    }

    requestDeletePeriod(name) {
        this.setState({
            deletePeriod: true,
            deletePassword: '',
            deletePeriodName: name,
            deleteMsg: '',
        })
    }

    requestCreatePeriod() {
        this.props.actions.fetchPeriodLevelOne()
        this.setState({
            createPeriod: true,
            createEditPeriod: true,
        })
    }

    requestEditPeriod() {
        const { objectivePeriods=[] } = this.props.okr.period
        const currentPeriod = objectivePeriods.filter(v => v.objectivePeriodId == this.props.params.periodId)[0]
        this.props.actions.fetchPeriodLevelOne(currentPeriod.periodTimeSpanId)
        this.setState({
            editPeriod: true,
            createEditPeriod: true,
        })
    }

    cancelRequestCreateEditPeriod() {
        this.setState({
            createEditPeriod: false
        }, () => {
            setTimeout(() => {
                this.setState({
                    createPeriod: false,
                    editPeriod: false
                })
            }, 200)
        })
        this.props.actions.resetPeriodLevel();
    }

    cancelRequestDeletePeriod() {
        this.setState({
            deletePeriod: false
        })
    }

    // 创建目标
    createObjective() {
        const {
            startingAmount,
            currentAmount,
            directorList,
            ...others,
        } = this.refs.objectiveCreate.state.field; // 从模态框中拉取填充的数据
        const { selectObjective } = this.refs.objectiveCreate.state;
        if (checkItemInput({startingAmount, currentAmount , ...others}) !== true) return;
        if (!util.isNull(selectObjective)) {
            others.parentObjectiveId = selectObjective.objectiveId;
        }
        info('创建中...');
        this.props.actions.createObjective({
            directorList: directorList.map(v => ({
                userId: v.coreUserProfileVO.userId
            })),
            startingAmount,
            currentAmount: startingAmount,
            ...others
        }, () => {
            success('创建成功!');
            const { query, pathname } = this.props.location;
            if (query.aboutMe || query.progressStatus > 1) {
                this.context.router.push({
                    pathname: this.props.location.pathname,
                    query: {
                        ...this.props.location.query,
                        aboutMe: false,
                        progressStatus: 1,
                    }
                });
            } else {
                this.fetchObjective();
            }

            if (this.props.app.naviStep == 3 && this.props.app.guide == 3) {
                this.props.actions.updateGuide(4);
            }
        });

        cancelRequestCreateItem.call(this);
    }

    requestCreateObjective() {
        util.track.call({mpModule: '目标::目标添加编辑弹窗'})
        this.setState({
            createObjective: true,
            createItem: true,
        })
    }

    requestCreateKeyResult(objectiveId) {
        this.setState({
            createKeyResult: true,
            createItem: true,
            objectiveId,
        });
    }

    handlePeriodChange(value) {
        const { query, pathname } = this.props.location;
        this.props.actions.resetObjective();
        this.context.router.push({
            query,
            pathname: `/okr/${value}/objectives`
        });
    }

    // 获取当前周期Id
    getCurPeriod(periods) {
        if (util.isNull(periods)) return null;
        return util.find(periods, item => item.default).objectivePeriodId || util.last(periods).objectivePeriodId
    }

    /**
     * 获取目标列表
     * @param {props}
     * @param {isDelete} 是否是删除后的更新
     * @param {isFilterFromTeam} 是否是在本团队内筛选后的更新
     *
     * @returns {undefined}
     */
    fetchObjective(props, isDelete, isFilterFromTeam) {
        const { periodId } = (props || this.props).params;
        const { userId, progressStatus, aboutMe } = (props || this.props).location.query;
        if (!periodId) return;
        if (!userId) this.props.actions.resetUser();

        this.isDelete = isDelete;
        this.isFilterFromTeam = isFilterFromTeam;

        this.props.actions.fetchObjective({ periodId, progressStatus, aboutMe });
    }

    // 获取周期
    fetchPeriod(props) {
        const _props = props || this.props;
        const { type, userId, teamId, projectTeamId } = _props.location.query;
        if (type == null) return;

        let ownerId = teamId;
        if (type == PERSONAL) ownerId = userId;
        if (type == GROUP) ownerId = projectTeamId;
        if (type == COMPANY) ownerId = null;
        this.props.actions.fetchPeriod({ type, ownerId });
    }

    // 获取导航
    fetchNav(props) {
        const { teamId } = (props || this.props).location.query;
        if (!teamId) return;

        this.props.actions.fetchTeamAncestorChildren(teamId);
    }

    // 获取用户信息
    fetchUserCoreProfile(props) {
        if (this.type(props) != PERSONAL) return;
        const { userId } = (props || this.props).location.query;
        if (!userId) return;

        this.props.actions.fetchUserCoreProfile(userId);
    }

    // 获取组成员
    fetchGroupMembers(props) {
        const { teamId, projectTeamId } = (props || this.props).location.query;
        if (!projectTeamId || !teamId) return;

        this.props.actions.fetchGroupMembers(teamId, projectTeamId);
    }

    // 获取当前团队成员列表
    fetchTeamMembers(props) {
        //if (this.type(props) == PERSONAL) return;
        const { teamId, type } = (props || this.props).location.query;
        if (type == GROUP) return;
        if (!teamId) return;

        //this.props.actions.resetTeamMembers();
        this.props.actions.fetchTeamMembers(teamId);
    }

    // 获取团队下项目组
    fetchTeamGroups(props) {
        const { teamId } = (props || this.props).location.query;
        if (!teamId) return;

        this.props.actions.fetchTeamGroups(teamId);
    }

    type(props) {
        return (props || this.props).location.query.type;
    }

    checkAncenstorDeep(_obj=[], deep) {
        let _deep = 0;
        let more = [];
        function reGroup(obj) {
            if (!obj || !obj.length) return;
            if (_deep >= 1 && _deep < deep - 3) {
                more.push(obj[0]);
            }
            if (_deep == deep - 3) {
                const child = [
                    {
                        teamName: '...',
                        children: obj,
                        more,
                    }
                ]
                _obj[0].children = child;
            }
            _deep += 1;
            reGroup(obj[0].children);
        }

        if (deep > 4) {
            reGroup(_obj);
        }

        return _obj;
    }

    // 渲染导航
    renderNav() {
        let deep = 0;
        function sortTeamTreeList(list=[]) {
            list = util.deepClone(list);
            for(var i=0;i<list.length;i++) {
                for(var j=0;j<list.length;j++) {
                    if (list[i].parentTeamId == list[j].teamId) {
                        list[j].children = [list[i]]
                        deep += 1;
                    }
                }
            }
            return list;
        }

        function filterRoot(team, teams) {
            if (util.isNull(team)) return [];
            return (sortTeamTreeList(teams).filter(t => t.teamId == team.teamId)[0] || {}).children;
        }

        const { teamVO } = this.props.app.org;
        const { teamAncestorChildren={} } = this.props.team;
        const { ancestorTeams=[], childrenTeams=[] } = teamAncestorChildren;
        const { teamMembers } = this.props.okr;
        let nav;
        if (this.type() == COMPANY) {
            nav = { children: childrenTeams, teamMembers };
        } else if (this.type() == PERSONAL) {
            nav = { ancestor: filterRoot(teamVO, ancestorTeams), teamMembers: teamMembers.filter(u => u.userId != this.props.location.query.userId) };
        } else {
            nav = {
                ancestor: filterRoot(teamVO, ancestorTeams),
                children: childrenTeams,
                teamMembers,
            };
        }

        const { coreProfile } = this.props.user;
        const { teamId: curTeam } = this.props.location.query;

        const hasOtherTeamUsers = !util.isNull(nav.teamMembers);
        const teamOtherUserEvts = hasOtherTeamUsers? {
            onMouseEnter: () => this.setState({ showOtherTeamUsers: true }),
            onMouseLeave: () => this.setState({ showOtherTeamUsers: false }),
        } : {};

        function renderAncestorTree(children, more) {
            if (util.isNull(children)) return null;
            return (
                <ul
                    className={style.ancestor}
                >
                    {
                        children.map((team, i) => {
                            const evts = team.more? {
                                onMouseEnter: () => this.setState({ showMore: true }),
                                onMouseLeave: () => this.setState({ showMore: false }),
                            }: {};

                            const hasChildren = Array.isArray(this.state.otherTeamChildren[team.teamId]) && this.state.otherTeamChildren[team.teamId].length > 0;
                            return (
                                <li key={i}>
                                    {
                                        !team.more?
                                            <Link
                                                to={curTeam == team.teamId && this.type() == 2 ? `${this.props.location.pathname}?${util.body(this.props.location.query)}` : `/okr?type=2&teamId=${team.teamId}`}
                                                className={cx({
                                                    [style.active]: curTeam == team.teamId && this.type() == 2,
                                                    [style['has-children']]: hasChildren,
                                                })}
                                                onMouseEnter={() => this.setState({ showOtherTeam: team.teamId })}
                                                onMouseLeave={() => this.setState({ showOtherTeam: null })}
                                            >
                                                <div>
                                                    {
                                                        hasChildren?
                                                            <i/>: null
                                                    }
                                                    <span>{team.teamName}</span>
                                                </div>
                                            </Link>: (
                                                <div className={style['more-tab']}>
                                                    <span>{team.teamName}</span>
                                                    <ul className={style['more-ancestor']}>
                                                        {
                                                            team.more.map((v, i) => (
                                                                <li key={i}>
                                                                    <Link to={`/okr?type=2&teamId=${v.teamId}`}>
                                                                        <span>{ v.teamName }</span>
                                                                    </Link>
                                                                </li>
                                                            ))
                                                        }
                                                    </ul>
                                                </div>
                                            )
                                    }
                                    {
                                        renderAncestorTree.call(this, team.children, team.more)
                                    }
                                    {
                                        (hasChildren && this.state.showOtherTeam == team.teamId)? (
                                            <ul
                                                className={style['other-team-children']}
                                                onMouseEnter={() => this.setState({ showOtherTeam: team.teamId })}
                                                onMouseLeave={() => this.setState({ showOtherTeam: null })}
                                            >
                                                {
                                                    this.state.otherTeamChildren[team.teamId].map(t => (
                                                        <li key={t.teamId}>
                                                            <Link
                                                                to={`/okr?type=2&teamId=${t.teamId}`} label={t.teamName} />
                                                        </li>
                                                    ))
                                                }
                                            </ul>
                                        ) : null
                                    }
                                </li>
                            )})
                    }
                </ul>
            );
        }

        nav.ancestor = this.checkAncenstorDeep(nav.ancestor, deep);

        return (
            <ul className={style.nav}>
                <li className={style['org-nav']}>
                    <Link
                        to={this.type() == COMPANY ? `${this.props.location.pathname}?${util.body(this.props.location.query)}`: (util.isNull(teamVO)? null: `/okr?type=${COMPANY}&teamId=${teamVO.teamId}`)} label="公司目标"
                        className={cx({
                            [style.active]: this.type() == COMPANY,
                        })}
                    />
                </li>
                {
                    !util.isNull(nav.ancestor) ? renderAncestorTree.call(this, nav.ancestor) : null
                }
                {
                    (!util.isNull(nav.children) && this.type() != GROUP) ?
                        <li
                            onMouseEnter={() => this.setState({ showChildren: true })}
                            onMouseLeave={() => this.setState({ showChildren: false })}
                            className={style.children}
                        >
                            <span>下属部门</span>
                            {
                                this.state.showChildren ?
                                    <ul>
                                        {
                                            nav.children.map((team, i) => (
                                                <li key={i}>
                                                    <Link
                                                        to={`/okr?type=${TEAM}&teamId=${team.teamId}`}
                                                    >
                        <span>
                          <Avatar
                              team
                              width={25}
                          />
                          <span>{team.teamName}</span>
                        </span>
                                                    </Link>
                                                </li>
                                            ))
                                        }
                                    </ul>: null
                            }
                        </li>: null
                }
                {
                    !util.isNull(this.props.okr.teamGroups) ? (
                        <li
                            className={cx({
                                [style.children]: !util.isNull(this.type() == GROUP ? this.props.okr.teamGroups.filter(g => g.projectTeamId != this.props.location.query.projectTeamId) : this.props.okr.teamGroups),
                            })}
                            onMouseEnter={() => this.setState({ showTeamGroups: true })}
                            onMouseLeave={() => this.setState({ showTeamGroups: false })}
                        >
                            {
                                this.type() == GROUP ? ((() => {
                                    const g = this.props.okr.teamGroups.filter(g => g.projectTeamId == this.props.location.query.projectTeamId)[0];
                                    return (
                                        <Link to={`/okr/?type=${GROUP}&teamId=${g.teamId}&projectTeamId=${g.projectTeamId}`}>
                      <span>
                        {
                            g.projectTeamName
                        }
                      </span>
                                        </Link>
                                    );
                                })()): (
                                    <span>下属项目组</span>
                                )
                            }
                            {
                                (this.state.showTeamGroups && !util.isNull(this.type() == GROUP ? this.props.okr.teamGroups.filter(g => g.projectTeamId != this.props.location.query.projectTeamId) : this.props.okr.teamGroups)) ? (
                                    <ul>
                                        {
                                            (this.type() == GROUP ? this.props.okr.teamGroups.filter(g => g.projectTeamId != this.props.location.query.projectTeamId) : this.props.okr.teamGroups).map((g, i) => (
                                                <li key={i}>
                                                    <Link to={`/okr?type=${GROUP}&projectTeamId=${g.projectTeamId}&teamId=${g.teamId}`}>
                            <span>
                              <Avatar
                                  team
                                  width={25}
                              />
                              <span>{g.projectTeamName}</span>
                            </span>
                                                    </Link>
                                                </li>
                                            ))
                                        }
                                    </ul>
                                ) : null
                            }
                        </li>
                    ) : null
                }
                {
                    !util.isNull(this.props.okr.groupMembers) ? (
                        <li
                            className={style['team-memebers']}
                            onMouseEnter={() => this.setState({ showGroupMembers: true })}
                            onMouseLeave={() => this.setState({ showGroupMembers: false })}
                        >
                            <span>项目组成员</span>
                            {
                                this.state.showGroupMembers ? (
                                    <ul>
                                        {
                                            this.props.okr.groupMembers.map((u, i) => (
                                                <li key={i}>
                                                    <Link to={`/okr?type=${PERSONAL}&userId=${u.userId}&teamId=${u.teamVO.teamId}`}>
                            <span>
                              <Avatar
                                  width={25}
                                  src={u.avatarUrl}
                              />
                              <span>{u.fullName}</span>
                            </span>
                                                    </Link>
                                                </li>
                                            ))
                                        }
                                    </ul>
                                ) : null
                            }
                        </li>
                    ) : null
                }
                {
                    (!util.isNull(nav.teamMembers) && this.type() != PERSONAL)? (
                        <li
                            onMouseEnter={() => this.setState({ showTeamMemebers: true })}
                            onMouseLeave={() => this.setState({ showTeamMemebers: false })}
                            className={style['team-memebers']}
                        >
                            <span>团队成员目标</span>
                            {
                                this.state.showTeamMemebers ?
                                    <ul>
                                        {
                                            nav.teamMembers.map((user, i) => (
                                                <li key={i}>
                                                    <Link
                                                        to={`/okr?type=${PERSONAL}&userId=${user.userId}&teamId=${user.teamVO.teamId}`}
                                                    >
                          <span>
                            <Avatar
                                width={25}
                            />
                            <span>{user.fullName}</span>
                          </span>
                                                    </Link>
                                                </li>
                                            ))
                                        }
                                    </ul>: null
                            }
                        </li>
                    ): null
                }
                {
                    (!util.isNull(coreProfile) && this.type() == PERSONAL)?
                        <li
                            className={style['team-user']}
                            {...teamOtherUserEvts}
                        >
                            {
                                hasOtherTeamUsers ?
                                    <i/>: null
                            }
                            <span>{`${coreProfile.fullName}的目标`}</span>
                            {
                                (hasOtherTeamUsers && this.state.showOtherTeamUsers) ? (
                                    <ul>
                                        {
                                            nav.teamMembers.map((user, i) => (
                                                <li key={i}>
                                                    <Link
                                                        to={`/okr?type=${PERSONAL}&userId=${user.userId}&teamId=${user.teamVO.teamId}`}
                                                    >
                            <span>
                              <Avatar
                                  width={25}
                              />
                              <span>{user.fullName}</span>
                            </span>
                                                    </Link>
                                                </li>
                                            ))
                                        }
                                    </ul>
                                ) : null
                            }
                        </li>
                        : null
                }
            </ul>
        );
    }

    // 渲染目标
    // 1. 目标总进度
    // 2. 目标列表
    renderObjective() {
        return (
            <div className={style.objective}>
                { this.renderObjectiveTotal() }
                { this.renderObjectiveList() }
            </div>
        );
    }


    componentDidUpdate(prevProps, prevState) {
        const { objective } = this.props.okr;
        const { objectiveVOList} = objective;
        const { objective:prevObjective = {} } = prevProps.okr;
        const { objectiveVOList: prevObjectiveVOList} = prevObjective;
        if(this.scrollId && !util.isShallowEqual(prevObjectiveVOList,objectiveVOList)){
            setTimeout(()=> {
                const id = this.scrollId;
                this.scrollId = null;
                const item = this.refItems[id];
                const offset = findDOMNode(item).offsetTop;
                this.context.onContentScroll(offset);
            }, 0)
        }

    }
    setScrollId = (id) => {
        this.scrollId = id;
    }
    // 渲染目标列表
    renderObjectiveList() {
        const { userId } = this.props.location.query;
        const { objective, period } = this.props.okr;
        const { thumbup, objectiveVOList, objectiveEditable, objectiveDeletable, objectiveCreatable,objectiveReadable } = objective;
        const { creatable, objectivePeriods } = period;
        // 周期为空
        if (Array.isArray(objectivePeriods) && !objectivePeriods.length) {
            return (
                <div className={cx(style['objective-null'], {
                    [style['has-btn']]: creatable,
                })}>
                    <div style={{ borderRadius: '50%', backgroundImage: `url(${IMAGES_PATH}/objective-null.png)`, backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', width: '160px', height: '160px' }}/>
                    <p style={{ marginTop: '15px', fontSize: '18px', color: 'rgb(153, 153, 153)' }}>{userId?(util.isEqual(userId, u.userId)? '您': '该同事') :'该团队内'}暂未填写目标</p>
                    {
                        creatable? <Button style={{ width: '130px', height: '40px', marginTop: '15px' }} blueLine label="创建周期" onClick={::this.requestCreatePeriod} />: null
                    }
                </div>
            );
        }

        if(objectiveReadable == false){
            return (
                <div className={cx(style['objective-null'], {
                    [style['has-btn']]: objectiveCreatable && objectiveVOList
                })}>
                    <div style={{ borderRadius: '50%', backgroundImage: `url(${IMAGES_PATH}/objective-null.png)`, backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', width: '160px', height: '160px' }}/>
                    <p style={{ marginTop: '15px', fontSize: '18px', color: 'rgb(153, 153, 153)' }}>当前周期的目标你没有权限查看</p>
                </div>
            );
        }

        // 目标为空
        if (Array.isArray(objective.objectiveVOList) && !objectiveVOList.length) {
            return (
                <div className={cx(style['objective-null'], {
                    [style['has-btn']]: objectiveCreatable && objectiveVOList
                })}>
                    <div style={{ borderRadius: '50%', backgroundImage: `url(${IMAGES_PATH}/objective-null.png)`, backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', width: '160px', height: '160px' }}/>
                    <p style={{ marginTop: '15px', fontSize: '18px', color: 'rgb(153, 153, 153)' }}>当前周期尚无符合条件的目标</p>
                </div>
            );
        }

        if (util.isNull(objectiveVOList)) return <Loading style={{ marginTop: '30px' }} />;

        const findNext = (prevStyles, i) => {
            if (i > 4) return 0;
            const find = prevStyles.filter(s => s.key == objectiveVOList[i-1].objectiveId);
            if (find.length) {
                return find[0].style.y;
            }
            return 0;
        }

        return (
            <TransitionMotion
                willEnter={() => {
                    return {
                        y: 10,
                        x: 0,
                        opacity: 1,
                    };
                }}
                willLeave={() => {
                    // 只有删除后的更新有动画效果
                    if (!this.isDelete) return null;
                    return {
                        y: 0,
                        x: spring(1100, { stiffness: 100, damping: 20 }),
                        opacity: spring(0, { stiffness: 160, damping: 20 }),
                    };
                }}
                // 团队内筛选后没有动画
                styles={prevStyles => objectiveVOList.map((v, i) => {
                    return {
                        key: v.objectiveId,
                        style: {
                            y: this.isFilterFromTeam ? 0 : (i === 0 ? spring(0) : spring(findNext(prevStyles, i), { stiffness: 300, damping: 40 })),
                            x: 0,
                            opacity: 1,
                        },
                        data: v,
                    }
                })}
                defaultStyles={objectiveVOList.map(v => ({
                    key: v.objectiveId,
                    style: {
                        y: 10,
                        x: 0,
                        opacity: 1,
                    },
                    data: v,
                }))}
            >
                {
                    // 鼠标拖拽
                    styles => (
                        <ObjectiveDrag list={objectiveVOList} handleMove={this.props.actions.moveOkr} handleDone={(id) => {this.fetchObjective(this.props);this.setScrollId(id)}}>
                            {
                                styles.map((v, i) => {
                                    const { data: obj } = v;
                                    const { x, y, opacity } = v.style;
                                    return (
                                        <ObjectiveItem
                                            y={y} x={x}
                                            thumbup={thumbup[i]} // 点赞
                                            styles={{ transform: `translate3d(${x}px, ${y}px, 0)`, opacity, }}
                                            objectiveCreatable={objectiveCreatable}
                                            objectiveEditable={objectiveEditable}
                                            objectiveDeletable={objectiveDeletable}
                                            editObjective={() => requestEditObjective.call(this, obj)}
                                            editKeyResult={requestEditKeyResult.bind(this)}
                                            likeObjective={() => likeObjective.call(this, obj, thumbup[i])}
                                            likeKeyResult={likeKeyResult.bind(this, thumbup[i])}
                                            fetchObjective={::this.fetchObjective}
                                            requestCreateKeyResult={requestCreateKeyResult.bind(this)}
                                            obj={obj}
                                            index={i}
                                            {...obj}
                                            {...this.props}
                                            key={obj.objectiveId}
                                            ref={(item) => {this.refItems = {...(this.refItems||{}), [obj.objectiveId]: item}; }}
                                        />
                                    )
                                })
                            }
                        </ObjectiveDrag>
                    )
                }
            </TransitionMotion>
        );
    }
    renderTeamAdmin = () => {
        const {
            type,
            teamId,
        } = this.props.location.query;
        const { profile } = this.props.app;
        const {teamMembers} = this.props.okr;
        let teamMemberNumber = 1;
        if (type != TEAM) return;
        teamMembers.map((v,i)=>{
            if(profile.userId && profile.userId == v.userId){
                teamMemberNumber = v.teamVO.teamMemberNumber
                if(v.teamVO.teamId != teamId) return;
            }
        })

        if (teamMemberNumber === 1) return;
        return (
            <div style={{marginTop:'40px',marginBottom:'-40px', textAlign: 'right'}}>
                <Link
                    to={`/project/team/${teamId}`}
                >
                    <IconFont style={{ display: 'inline-block', verticalAlign: 'middle', height: '19px', marginRight: '4px' }} value="settings" />
                    <span style={{display: 'inline-block', verticalAlign: 'middle'}}>
            团队管理
          </span>
                </Link>
            </div>
        )
    }
    // 渲染总进度
    renderObjectiveTotal() {
        const { profile } = this.props.app;
        const { teamVO={} } = profile;
        const { objective, period } = this.props.okr;
        const { objectiveVOList } = objective;
        const { objectivePeriods, creatable, deletable } = period;
        const { totalProgress } = objective;
        const type = this.type();
        const { teamAncestorChildren={} } = this.props.team;
        const { ancestorTeams=[] } = teamAncestorChildren;
        let title = '';
        if (type == COMPANY) title = '公司';
        else if (type == TEAM) title = util.find(ancestorTeams, t => t.teamId == this.props.location.query.teamId).teamName;
        else if (type == PERSONAL) {
            const { coreProfile={} } = this.props.user;
            title = coreProfile.fullName;
        } else if (type == GROUP) {
            const groups = this.props.okr.teamGroups.filter(g => g.projectTeamId == this.props.location.query.projectTeamId);
            title = !util.isNull(groups) ? `${groups[0].projectTeamName}` : '';
        }
        const periodName = ((objectivePeriods||[]).find(v => v.objectivePeriodId == this.props.params.periodId)||{}).name;
        // 引导
        const { naviStep: step, guide } = this.props.app;
        return (
            <div className={style['objective-total']}>
                <div>
                    <h2>
                        {
                            title?
                                <span>{`${type == COMPANY ? title : (title + '的')}`}目标</span>
                                : null
                        }
                    </h2>
                    <div className={style['total-actions']}>
                        {
                            !util.isNull(objectivePeriods)?
                                <Select
                                    height={25}
                                    id="objectivePeriodId"
                                    className={style['objective-period']}
                                    value={this.props.params.periodId}
                                    onChange={::this.handlePeriodChange}
                                    list={objectivePeriods}
                                    item={item => <li key={item.objectivePeriodId} data-value={item.objectivePeriodId}>{item.name}</li>}
                                /> : null
                        }
                        {
                            (!creatable && !deletable)? null: (
                                <Menu ref="periodMenu">
                                    <Button
                                        blueSimpleLine
                                        style={{ borderColor: 'rgb(215, 222, 231)', marginLeft: '10px', height: '25px'}}
                                        icon="more"
                                    />
                                    <ActionList
                                        {...this.props}
                                        creatable={creatable}
                                        deletable={deletable}
                                        requestEditPeriod={::this.requestEditPeriod}
                                        requestCreatePeriod={::this.requestCreatePeriod}
                                        requestDeletePeriod={this.requestDeletePeriod.bind(this, periodName)}
                                    />
                                </Menu>
                            )
                        }
                        {
                            (step === 2 && guide == 2) ? (
                                <NextGuide
                                    left
                                    styles={{ left: '-156px',top: '32px'}}
                                    str="点击创建周期"
                                />
                            ) : null
                        }
                    </div>
                </div>
                {
                    (util.isNull(objectivePeriods) || (util.isNull(objectiveVOList) && !(teamVO.teamId == this.props.location.query.teamId && this.type() == TEAM)))? null: (
                        <div className={style['progress-info-wrapper']}>
                            <div className={style['progress-info']}>
                                {
                                    (objectiveVOList && !objectiveVOList.length)? (
                                        <div></div>
                                    ): (
                                        <div>
                                            <label>进度</label>
                                            <Progress
                                                className={style['total-progress']+' '+style['total-type-'+(
                                                    !totalProgress || +(totalProgress* 100) < 40 ? "1" :
                                                        +(totalProgress* 100) >= 40 && +(totalProgress* 100) < 75 ? "2" : "3"
                                                )]}
                                                line
                                                radius
                                                width={522}
                                                height={12}
                                                value={44}
                                                value={totalProgress? +(totalProgress* 100): 0}
                                                labelAnimation
                                            />
                                        </div>
                                    )
                                }
                                {
                                    (teamVO.teamId == this.props.location.query.teamId && this.type() == TEAM)?
                                        <div className={style['filter-from-team']}>
                                            {/* 团队目标 */}
                                            {
                                                (this.props.location.query.progressStatus > 1 || !((this.props.location.query.aboutMe === 'false' || !this.props.location.query.aboutMe)))?
                                                    <Button blueSimpleLine style={{ width: '64px', padding: '0px', height: '20px', borderColor: '#e3e7ef' }} label="回到全部" blueLine onClick={::this.handleCheckAllTeamObjective}/>: null
                                            }
                                            <Select
                                                style={{ width: '100px' }}
                                                height={20}
                                                value={this.props.location.query.progressStatus == null ? "0" : `${this.props.location.query.progressStatus-1}`}
                                                onChange={::this.handleChangeProgressStatus}
                                                list={[
                                                    '全部进度',
                                                    '尚未开始',
                                                    '正在进行',
                                                    '接近完成',
                                                ]}
                                                item={
                                                    (v, i) => (
                                                        <li key={i} data-value={i}>{v}</li>
                                                    )
                                                }
                                            />
                                            <Checkbox
                                                active={(this.props.location.query.aboutMe === 'false' || !this.props.location.query.aboutMe)? false: true}
                                                onClick={::this.handleToggleAboutMe}
                                                className={style.check}
                                                label="只看我负责的"
                                            />
                                        </div>: null
                                }
                            </div>
                        </div>
                    )
                }
            </div>
        );
    }

    // 文件上传
    upload(file) {
        const upload = new Upload(file.file)
        info('上传中...', true)
        upload.to({
            headers: {
                'X-Access-Token': cookie('X-Access-Token'),
                'X-Refresh-Token': cookie('X-Refresh-Token'),
            },
            path: "" // 上传路径
        })
        upload.on('progress', () => {})
        upload.on('end', res => {
            res = JSON.parse(res.responseText)
            if (/^2\d+$/.exec(res.code)) {
                success('上传成功!')
                renderObjective(); // 重新渲染目标和进度
                /* this.setState({
                  upload: true,
                  number: res.data.totalCount
                }) */
            }
            // 数据格式有误
            else if ('4000309' == res.code) {
                error("数据格式有误!")
                /* this.setState({
                  upload: false,
                  dataError: true
                })
                this.props.createDocument({ scenario: 3, documentName: this.state.file.name, storageStatus: 1 }, data => {
                  const { documentId, presignedUrl } = data
                  this.CSVDocument = documentId
                  this.props.fileUpload({
                    file: this.state.file,
                    url: presignedUrl,
                    cb: () => {
                      this.setState({
                        dataErrorHandle: true
                      })
                    }
                  })
                }) */
            }
            else {
                error("上传失败")
                /* this.setState({
                  upload: false,
                  error: res.errorInfo || res.msg
                }) */
            }
        })
    }

    render() {
        const { teamVO={} } = this.props.app.org;

        const { period, periodLevel, objective, history: okrHistory } = this.props.okr
        const { objectivePeriods=[] } = period
        const { objectiveCreatable, objectiveVOList,objectiveReadable } = (objective || {});
        const { one: periodLevelOne=[] } = periodLevel
        let { two: periodLevelTwo=[] } = periodLevel
        const {
            query
        } = this.props.location;
        // filter已创建的
        if (this.state.createPeriod) {
            if (periodLevelTwo.length) {
                periodLevelTwo = periodLevelTwo.filter((v,i) => objectivePeriods.every(item => item.name != v.name));
            }
        }

        // 周期是否可用
        const isPeriodTwoSelectable = periodLevelTwo.length && periodLevelTwo.some(v => objectivePeriods.every(item => item.name != v.name));

        // 周期按钮
        const periodActions = isPeriodTwoSelectable
            ? [
                'cancel',
                () => {
                    if (this.state.createPeriod) {
                        this.createPeriod();
                    } else {
                        this.updatePeriod();
                    }
                }
            ]
            : [
                'cancel'
            ];

        return (
            <div>
                {/* 目标导览的搜索 */}
                {
                    <div className={style['nav-bar']}>
                        <div>
                            <p className={style['nav-title']}>目标导览</p>
                            { this.renderNav() }
                        </div>
                        <div className={style.search}>
                            <label>前往其他团队/同事/项目组的目标</label>
                            <div className={style['icon-input']}>
                                <IconFont value='search' />
                                <SearchInput
                                    label="输入姓名/团队/项目组名称"
                                    onChange={::this.handleSearch}
                                    onFocus={::this.toggleSearch}
                                    onBlur={::this.toggleSearch}
                                    value={this.state.query}
                                    ref="searchInput"
                                />
                            </div>
                            {
                                (this.state.search && !this.state.stopSearch)?(
                                    <List
                                        close={() => {
                                            this.refs.searchInput.blur();
                                            this.setState({
                                                query: '',
                                                stopSearch: true,
                                            });
                                        }}
                                        onClick={(v) => {
                                            if (v.projectTeamId) {
                                                this.context.router.push(`/okr?type=${GROUP}&teamId=${v.teamId}&projectTeamId=${v.projectTeamId}`);
                                            }
                                            else if (v.teamId) {
                                                this.context.router.push(`/okr?type=${TEAM}&teamId=${v.teamId}`);
                                            } else {
                                                this.context.router.push(`/okr?type=${PERSONAL}&userId=${v.userId}&teamId=${v.teamVO.teamId}`);
                                            }
                                        }}
                                        className={style['recent-check-objective']}
                                        data={(() => {
                                            const obj = this.state.query ? this.props.okr.search : okrHistory;
                                            if (util.isNull(obj) || this.state.searching) return null;
                                            const { teamVOs=[], coreUserProfileVOs=[], projectTeamVOs=[] } = obj;
                                            const { teamVO } = this.props.app.org;
                                            return [
                                                ...teamVOs.filter(t => t.teamId != (teamVO || {}).teamId),
                                                ...coreUserProfileVOs,
                                                ...projectTeamVOs,
                                            ];
                                        })()}
                                        item={
                                            v => {
                                                // team
                                                if (v.teamId && !v.projectTeamId) {
                                                    return (
                                                        <Link
                                                            to={`/okr?type=${TEAM}&teamId=${v.teamId}`}
                                                            onClick={() => this.setState({ query: '', stopSearch: true })}
                                                        >
                              <span className={style['team-span']}>
                                <Avatar
                                    team
                                    width={36}
                                />
                                <span>{v.teamName}</span>
                              </span>
                                                        </Link>
                                                    );
                                                }

                                                // group
                                                if (v.projectTeamId) {
                                                    return (
                                                        <Link
                                                            to={`/okr?type=${GROUP}&teamId=${v.teamId}&projectTeamId=${v.projectTeamId}`}
                                                            onClick={() => this.setState({ query: '', stopSearch: true })}
                                                        >
                              <span className={style['team-span']}>
                                <Avatar
                                    team
                                    width={36}
                                />
                                <span>{v.projectTeamName}</span>
                              </span>
                                                        </Link>
                                                    );
                                                }

                                                // user
                                                return (
                                                    <Link
                                                        to={`/okr?type=${PERSONAL}&userId=${v.userId}&teamId=${v.teamVO.teamId}`}
                                                        onClick={() => this.setState({ query: '', stopSearch: true })}
                                                    >
                            <span className={style['user-span']}>
                              <span>
                                <Avatar
                                    src={v.avatarUrl}
                                    width={36}
                                />
                                <span>{v.fullName}</span>
                              </span>
                              <span className={style['title']}>{v.jobTitleName || ''}</span>
                            </span>
                                                    </Link>
                                                );
                                            }
                                        }
                                    />
                                ): null
                            }
                            {/*
                this.state.search?
                <div className={cx(style['recent-check-objective'], { [style['recent-search']]: this.state.query.trim() })}>
                  {
                    !this.state.query.trim()?
                    <h2>最近查看</h2>: null
                  }
                  <Search
                    ctx={this}
                    searching={this.state.searching}
                    query={this.state.query}
                    okrHistory={okrHistory}
                    {...this.props}
                    router={this.context.router}
                  />
                </div>
                : null
              */}
                        </div>
                    </div>
                }
                { this.renderTeamAdmin() }

                {
                this.renderObjective()
                }

                {
                    (!objectiveCreatable || (objectivePeriods && !objectivePeriods.length))? null: (
                        (objectiveCreatable && objectiveVOList && !objectiveVOList.length)? (
                            <div>
                                <Button
                                    style={{ width: '130px', height: '40px', marginTop: '-81px', position: 'absolute', left: '50%', marginLeft: '-68px' }}
                                    blueLine
                                    label="创建目标"
                                    onClick={() => {
                                        this.requestCreateObjective.call(this);
                                        if (this.props.app.naviStep == 3 && this.props.app.guide == 2) {
                                            this.props.actions.setStepGuide(3);
                                        }
                                    }}
                                />
                            </div>
                        ): (
                            <div>
                                <Button
                                    style={{ width: '146px', height: '45px', marginTop: '30px', display: "inline-block", verticalAlign: "middle" }}
                                    blue
                                    label="创建目标"
                                    onClick={() => {
                                        this.requestCreateObjective.call(this);
                                        if (this.props.app.naviStep == 3 && this.props.app.guide == 2) {
                                            this.props.actions.setStepGuide(3);
                                        }
                                    }}
                                />
                                {/* <div style={{ width: '146px', height: '45px', marginTop: '29px', display: "inline-block", verticalAlign: "middle" }}>
                  <FileUpload
                    className={style['pick-file']}
                    link
                    placeholder="导入OKR"
                    onChange={::this.upload}
                  />
                </div> */}
                            </div>
                        )
                    )
                }
                {
                    (this.props.app.naviStep == 3 && this.props.app.guide == 2) ? (
                        <NextGuide
                            right
                            styles={(objectiveVOList && !objectiveVOList.length) ? {marginTop: '-78px', marginLeft: '79px', left: '50%'} : { marginTop: '-39px', marginLeft: '162px' }}
                            str="点击这里"
                        />
                    ) : null
                }
                <Modal
                    onRequestClose={() => {
                        cancelRequestCreateItem.call(this);
                        if (this.state.createObjective) {
                            if (this.props.app.naviStep == 3 && this.props.app.guide == 3) {
                                this.props.actions.setStepGuide(1);
                            }
                        } else {
                            if (this.props.app.naviStep == 4 && this.props.app.guide == 3) {
                                this.props.actions.setStepGuide(1);
                            }
                        }
                    }}
                    active={this.state.createItem}
                    title={this.state.createObjective? "创建目标": "添加关键结果"}
                    className={style['objective-create-modal']}
                    actions={[
                        'cancel',
                        () => {
                            if (this.state.createObjective) this.createObjective();
                            else createKeyResult.call(this);
                        }
                    ]}
                >
                    {/* 目标/结果 —— 模态框新增 */}
                    <ObjectiveCreate
                        ref="objectiveCreate"
                        objectiveType={this.type()}
                        objectiveId={this.state.objectiveId}
                        createObjective={this.state.createObjective}
                        createKeyResult={this.state.createKeyResult}
                        requestEditKeyResult={requestEditKeyResult.bind(this)}
                        submit={() => {
                            if (this.state.createObjective) this.createObjective(); // 提交创建的目标
                            else createKeyResult.call(this); // 提交创建的关键结果
                        }}
                        {...this.props}
                    />
                </Modal>
                <Modal
                    title={`确认删除目标周期【${this.state.deletePeriodName}】`}
                    onRequestClose={::this.cancelRequestDeletePeriod}
                    active={this.state.deletePeriod}
                >
                    <div className={style['delete-area']}>
                        <p>删除当前目标后期，讲同时删除当前周期的所有目标、关键结果、批注和更新记录。<span>此操作不可逆</span></p>
                        <p>如确定要删除，请输入登录密码，并点击下方按钮：</p>
                        <input type="password" value={this.state.deletePassword} onChange={(e)=>this.setState({deletePassword:e.target.value, deleteMsg:''})}/>
                        <div className={style['delete-msg']}>{this.state.deleteMsg}</div>
                        <Button style={{ width: '100%', marginTop: '10px' }} disabled={!this.state.deletePassword} blue  label="删除目标周期" onClick={::this.deletePeriod} />
                    </div>
                </Modal>
                <Modal
                    onRequestClose={() => {
                        this.cancelRequestCreateEditPeriod();
                        if (this.props.app.naviStep == 2 && this.props.app.guide == 3) {
                            this.props.actions.setStepGuide(1);
                        }
                    }}
                    active={this.state.createEditPeriod}
                    actions={periodActions}
                    title={this.state.createPeriod? '创建目标周期': '编辑目标周期'}
                >
                    <div className={style['select-period-dialog-body']}>
                        <div className={style['label-select']}>
                            <label>周期长度</label>
                            {
                                periodLevelOne.length? (
                                    <Select
                                        id="type"
                                        style={{ width: '160px' }}
                                        value={`${periodLevelOne.filter(v => v.default)[0].type}`}
                                        onChange={::this.handleChangeSelectPeriodLevel}
                                        item={(v, i) => <li key={i} data-value={v.type}>{v.name}</li>}
                                        list={periodLevelOne}
                                    />
                                ): null
                            }
                        </div>
                        <div className={style['label-select']}>
                            <label>选择周期</label>
                            {
                                isPeriodTwoSelectable ? (
                                    <Select
                                        id="name"
                                        style={{ width: '160px' }}
                                        value={(() => {
                                            let item;
                                            let find = periodLevelTwo.filter(v => v.default);
                                            if (find.length) {
                                                item = find[0];
                                            } else {
                                                let filterPeriodIndex = indexOf(periodLevel.two, v => v.default);
                                                find = periodLevel.two.slice(filterPeriodIndex).filter(v => objectivePeriods.every(item => item.name != v.name));
                                                if (find.length) item = find[0];
                                                else {
                                                    find = periodLevel.two.slice(0, filterPeriodIndex).filter(v => objectivePeriods.every(item => item.name != v.name));
                                                    if (find.length) item = find[0];
                                                }
                                            }
                                            this.editPeriodItem = item;
                                            return (item || {}).name;
                                        })()}
                                        onChange={::this.handleChangeSelectPeriodLevelTwo}
                                        item={(v,i) => <li key={i} data-value={v.name}>{v.name}</li>}
                                        list={periodLevelTwo}
                                    />
                                ): null
                            }
                            {
                                (this.state.createEditPeriod && Array.isArray(periodLevel.two) && !isPeriodTwoSelectable) ? <div>没有可用周期了..</div> : null
                            }
                        </div>
                    </div>
                </Modal>
                <Modal
                    active={this.state.editItem}
                    title={this.state.editObjective? '编辑目标': '编辑关键结果'}
                    onRequestClose={() => {
                        cancelRequestEditItem.call(this);
                        if (this.props.app.naviStep == 6 && this.props.app.guide == 3) {
                            this.props.actions.setStepGuide(1);
                        }
                    }}
                    actions={[
                        'cancel',
                        () => {
                            if (this.state.editObjective) {
                                updateObjective.call(this);
                            } else {
                                updateKeyResult.call(this);
                            }
                        }
                    ]}
                >
                    {/* 目标/结果 —— 模态框编辑 */}
                    <ObjectiveCreate
                        ref="objectiveEdit"
                        objectiveType={this.type()}
                        onRequestClose={cancelRequestEditItem.bind(this)}

                        submit={() => {
                            if (this.state.editObjective) {
                                updateObjective.call(this);
                            } else {
                                updateKeyResult.call(this);
                            }
                        }}
                        objective={this.state.objective}
                        keyResult={this.state.keyResult}
                        editObjective={this.state.editObjective}
                        editKeyResult={this.state.editKeyResult}
                        fetchObjective={::this.fetchObjective}
                        {...this.props}
                    />
                </Modal>
            </div>
        );
    }
}

function indexOf(arr, fn) {
    for(let i = 0;i < arr.length; i++) {
        if (fn(arr[i])) return i;
    }
    return null;
}
